import axios from 'axios';
import {getCookie, removeCookie} from '../libs/cookie';
import store from '../store/index';
import router from '@/router';
import util from '@/libs/util'
import {Message,MessageBox } from 'element-ui';

export const http = axios.create({
  // baseURL:'/admin',//开发
  baseURL: '',//打包发布
  timeout: 30000
})
// //请求拦截
http.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['token'] = getCookie('token');
    return config;
  }
}, error => {
  return Promise.reject(error);
});
//响应拦截
http.interceptors.response.use(res => {
  //token过期
  if (res.data && res.data.code === 401) {
    MessageBox.confirm('登录信息已过期,请重新登录', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      callback: function (action, instance) {
        if (action === "confirm") {
          //清除登录信息
          util.clearLoginInfo();
          router.push({name: 'login'});
        }
      }
    });
  }
  // //没有权限
  // if (res.data && res.data.code === 405) {
  //     Message.error("权限不足,请联系管理员!")
  //
  // }
  return res.data
}, error => {
  return Promise.reject(error)
});

let ajax = {}
//get请求
ajax.doAjaxGet = function (url, param, success) {
  url = url.indexOf('?') == '-1' ? url + '?_=' + (new Date()).getTime() : url + '&_=' + (new Date()).getTime()
  return http.get(url, param).then(function (res) {
    if (typeof success == 'function') {
      success(res);
    }
  });
}
//post 请求data:{}  param:{}
ajax.doAjaxPost = function (url, data, success) {
  return axios.post(url, data).then(function (res) {
    if (typeof success == 'function') {
      success(res.data);
    }
  });
}

export default ajax

